package com.rkjoeson.player.adapter;

import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.PLOnErrorListener;
import com.pili.pldroid.player.PLOnInfoListener;
import com.pili.pldroid.player.widget.PLVideoView;
import com.rkjoeson.player.R;
import com.rkjoeson.player.constants.QiniuPlayerEventConstants;
import com.rkjoeson.player.data.ReactShortVideoData;
import com.rkjoeson.player.utils.NetworkUtils;
import com.rkjoeson.player.utils.ToastUtils;

import java.util.ArrayList;

public class ShortVideoAdapter extends RecyclerView.Adapter<ShortVideoAdapter.ShortVideoViewHolder> {

    private Context context;
    private ArrayList<ReactShortVideoData> data;
    private RCTEventEmitter mEventEmitter;
    private OnItemClickListener onItemClickListener;

    public ShortVideoAdapter(Context context, ArrayList<ReactShortVideoData> data, RCTEventEmitter mEventEmitter) {
        this.context = context;
        this.data = data;
        this.mEventEmitter = mEventEmitter;
    }

    @NonNull
    @Override
    public ShortVideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View itemView = layoutInflater.inflate(R.layout.short_video_item, parent, false);
        return new ShortVideoViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull ShortVideoViewHolder holder, int position) {
        ReactShortVideoData dataItem = data.get(position);

        Glide.with(context).load(dataItem.getThumbnail()).into(holder.coverView);
        holder.plVideoView.setCoverView(holder.coverView);
        holder.plVideoView.setVideoURI(Uri.parse(dataItem.getVideoUrl()));

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(v, position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }


    class ShortVideoViewHolder extends RecyclerView.ViewHolder {

        PLVideoView plVideoView;
        ImageView coverView;

        ShortVideoViewHolder(@NonNull View itemView) {
            super(itemView);
            plVideoView = itemView.findViewById(R.id.VideoView);
            coverView = itemView.findViewById(R.id.CoverView);

            View loadingView = itemView.findViewById(R.id.LoadingView);

            AVOptions options = new AVOptions();
            options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 10 * 1000);
            options.setInteger(AVOptions.KEY_MEDIACODEC, AVOptions.MEDIA_CODEC_SW_DECODE);

            plVideoView.setAVOptions(options);
            plVideoView.setDisplayAspectRatio(PLVideoView.ASPECT_RATIO_PAVED_PARENT);
            plVideoView.setLooping(true);
            plVideoView.setBufferingIndicator(loadingView);

            plVideoView.setOnPreparedListener(i -> {
                plVideoView.start();
                mEventEmitter.receiveEvent(plVideoView.getId(), QiniuPlayerEventConstants.ON_LOADING, Arguments.createMap());
            });
            plVideoView.setOnInfoListener((i, i1) -> {
                switch (i) {
                    case PLOnInfoListener.MEDIA_INFO_VIDEO_RENDERING_START:
                        break;

                    case PLOnInfoListener.MEDIA_INFO_BUFFERING_END:
                        mEventEmitter.receiveEvent(plVideoView.getId(), QiniuPlayerEventConstants.ON_PLAYING, Arguments.createMap());
                        break;

                    case PLOnInfoListener.MEDIA_INFO_BUFFERING_START:
                        mEventEmitter.receiveEvent(plVideoView.getId(), QiniuPlayerEventConstants.ON_LOADING, Arguments.createMap());
                        break;
                }
            });
            plVideoView.setOnVideoSizeChangedListener((width, height) -> Log.d("播放器", "播放器大小变化: " + width + "," + height));
            plVideoView.setOnBufferingUpdateListener(i -> Log.d("播放器", "buffer更新: " + i));
            plVideoView.setOnCompletionListener(() -> {
            });
            plVideoView.setOnSeekCompleteListener(() -> Log.d("播放器", "onSeekComplete !"));
            plVideoView.setOnErrorListener(i -> {
                Log.d("播放器", "播放器发生错误, 错误状态码 = " + i);
                switch (i) {
                    case PLOnErrorListener.ERROR_CODE_IO_ERROR:
                        boolean isNetworkAvailable = NetworkUtils.isNetworkAvailable(context);
                        Log.d("播放器网络", isNetworkAvailable + "");
                        if (!isNetworkAvailable) {
                            ToastUtils.showMessage(context, "网路错误...");
                        }
                        break;
                }
                WritableMap event = Arguments.createMap();
                event.putInt("error", i);
                mEventEmitter.receiveEvent(plVideoView.getId(), QiniuPlayerEventConstants.ON_PLAYER_ERROR, Arguments.createMap());
                return true;
            });
        }
    }

    public interface OnItemClickListener {

        void onItemClick(View view, int position);
    }
}
